package com.example.lock.redisLock;

import com.example.lock.DistributedLock;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class RedisProcessor implements Runnable {

    private static final int REDIS_EXPIRE_SUCCESS = 1;

    private  DistributedLock distributedLock;

    private String identify;

    RedisProcessor(String key, String value, Long lockTime, DistributedLock distributedLock,String identify) {
        this.key = key;
        this.value = value;
        this.lockTime = lockTime;
        this.signal = Boolean.TRUE;
        this.distributedLock = distributedLock;
        this.identify = identify;
    }

    private String key;

    private String value;

    private Long lockTime;

    //线程关闭的标记
    private volatile Boolean signal;

    void stop() {
        this.signal = Boolean.FALSE;
    }

    public void run() {

        Long waitTime = lockTime * 1000 * 2 / 3;
        int index =1;
        while (signal) {
            try {
                Thread.sleep(waitTime);
                if (distributedLock.extendLockTime(key, lockTime*1000, identify)) {
                    System.out.println("守护线程第"+index+"续期");
                } else {
                    System.out.println("守护线程停止");
                    this.stop();
                }
                index +=index;
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (Exception e) {
                log.error("SurvivalClamProcessor run error", e);
            }
        }
    }


    public static void main(String[] args) throws Exception {
        SimpleJedisLock jedisLock = new SimpleJedisLock();
        String lockName = "myTestLock";

        String identify = jedisLock.acquireLock(lockName, 5000L, 30000L);

        RedisProcessor RedisProcessor
                = new RedisProcessor(lockName, "1", 30L,jedisLock,identify);
        Thread survivalThread = new Thread(RedisProcessor);
        survivalThread.setDaemon(Boolean.TRUE);
        survivalThread.start();
        System.out.println("守护进程启动");

        System.out.println("主线程加锁");
        Thread.sleep(50000);

        jedisLock.release(lockName,identify);
        System.out.println("主线程释放锁");
        RedisProcessor.stop();
        survivalThread.interrupt();
    }
}
